package com.nbsaas.boot.article.rest.resource;

import com.nbsaas.boot.article.api.apis.ArticleApi;
import com.nbsaas.boot.article.data.entity.Article;
import com.nbsaas.boot.article.api.domain.request.ArticleRequest;
import com.nbsaas.boot.article.api.domain.response.ArticleResponse;
import com.nbsaas.boot.article.api.domain.simple.ArticleSimple;
import com.nbsaas.boot.article.rest.convert.ArticleSimpleConvert;
import com.nbsaas.boot.article.rest.convert.ArticleEntityConvert;
import com.nbsaas.boot.article.rest.convert.ArticleResponseConvert;
import com.nbsaas.boot.article.data.repository.ArticleRepository;

import java.io.Serializable;
import com.nbsaas.boot.jpa.data.core.BaseResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.Resource;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;

import java.util.function.Function;
import com.nbsaas.boot.rest.enums.StoreState;
import com.nbsaas.boot.rest.request.RequestId;
import java.util.Optional;
import com.nbsaas.boot.rest.response.ResponseObject;
/**
*   -业务接口实现
*/
@Transactional
@Service
public class ArticleResource extends BaseResource<Article,ArticleResponse, ArticleSimple, ArticleRequest>  implements ArticleApi {

    @Resource
    private ArticleRepository articleRepository;

    @Override
    public JpaRepositoryImplementation<Article, Serializable> getJpaRepository() {
        return articleRepository;
    }

    @Override
    public Function<Article, ArticleSimple> getConvertSimple() {
        return new ArticleSimpleConvert();
    }

    @Override
    public Function<ArticleRequest, Article> getConvertForm() {
        return new ArticleEntityConvert();
    }

    @Override
    public Function<Article, ArticleResponse> getConvertResponse() {
        return new ArticleResponseConvert();
    }




    @Override
    public ResponseObject<ArticleResponse> create(ArticleRequest request) {
        request.setStoreState(StoreState.normal);
        return super.create(request);
   }

    @Override
    public ResponseObject<?> delete(RequestId request) {

        ResponseObject<?> result = new ResponseObject<>();
        Optional<Article> optional = getJpaRepository().findById(request.getId());
        if (!optional.isPresent()) {
            result.setCode(501);
            result.setMsg("无效id");
            return result;
        }
        Article bean = optional.get();
        bean.setStoreState(StoreState.draft);
        return result;

    }
}


